import request from './request'
import tip from './tip'
import api from '../api/api';

/**
 * 获取七牛token
 */
export function getQiniuToken() {
 //  let res = await api.qiniuToken()
	// return res
	return api.qiniuToken({query:{}})
}

export function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3|0x8)
    return v.toString(16)
  })
}

/**
 *上传图片
 */
export const uploadImage = (num) => {
  return chooseImage(num).then(res => {
    const tempFilePaths = res.tempFilePaths
    let arr = new Array(tempFilePaths.length)
    let count = 0
    tip.loading('上传中')
    return new Promise((resolve,reject)=>{
      for (let i in tempFilePaths) {
        qiniuUpload(tempFilePaths[i]).then((res) => {
          arr[i] = res.imageUrl
          count++
          if (count == arr.length) {
            tip.loaded()
            resolve(arr)
          }
        })
      }
    })
  })
}

//上传到七牛
async function qiniuUpload(filePath){
  let res = await getQiniuToken()

  let fileName = guid()+'.png'
  let baseUrl = res.data.baseUrl
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: res.data.uploadUrl,
      filePath: filePath,
      name:"file",
      // header: {"content-type": "multipart/form-data"}, // 设置请求的 header
      formData: {key: fileName, token: res.data.token}, // HTTP 请求中其他额外的 form data
      success: (res)=>{
        let a = JSON.parse(res.data)
        res.imageUrl = baseUrl + "/" + a.key
        resolve(res)
		  console.log(fileName,'fileNamefileName')
      },
      fail: (err)=> {
        reject()
      }
    })
  })
}
/**
 *选择图片
 */
export function chooseImage(num){
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: num, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function(res) {
        resolve(res)
      },
      fail: function(err){
        reject('选择图片失败')
      }
    })
  })
}
